import threading

from PySide2.QtWidgets import QDialog, QVBoxLayout, QTextEdit, QPushButton, QFileDialog, QSizePolicy
from PySide2.QtCore import Qt, QTimer
import os


def trim_log_file(log_file_path, max_size_kb=300):
    """
    检查日志文件的大小，如果超过指定大小，则删除最旧的文本。

    :param log_file_path: 日志文件的路径
    :param max_size_kb: 最大文件大小（单位：KB）
    """
    try:
        if not os.path.exists(log_file_path):
            return

        max_size_bytes = max_size_kb * 1024

        with open(log_file_path, 'r+', encoding='utf-8') as file:
            content = file.read()
            file_size = len(content.encode('utf-8'))

            if file_size > max_size_bytes:
                # 计算需要删除的字节数
                bytes_to_remove = file_size - max_size_bytes

                # 从文件开头开始删除最旧的文本
                while file_size > max_size_bytes:
                    # 逐步删除最旧的行
                    lines = content.splitlines()
                    if not lines:
                        break
                    removed_line = lines.pop(0)
                    content = '\n'.join(lines) + '\n'
                    file_size = len(content.encode('utf-8'))

                # 将处理后的内容写回文件
                file.seek(0)
                file.write(content)
                file.truncate()
    except Exception as e:
        pass


class ShowLogWindow(QDialog):
    def __init__(self, log_file_path, parent=None):
        super(ShowLogWindow, self).__init__(parent)
        trim_log_file(log_file_path)
        self.log_file_path = log_file_path
        self.setWindowTitle("查看登录日志")
        self.setFixedSize(800, 600)  # 初始大小，用户可以调整
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.init_ui()
        self.load_last_lines()

    def init_ui(self):
        layout = QVBoxLayout()

        self.text_edit = QTextEdit(self)
        self.text_edit.setReadOnly(True)
        self.text_edit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        layout.addWidget(self.text_edit)

        self.close_button = QPushButton("关闭", self)
        self.close_button.clicked.connect(self.close)
        layout.addWidget(self.close_button)

        self.setLayout(layout)

    def load_last_lines(self, num_lines=None):
        if not os.path.exists(self.log_file_path):
            self.text_edit.append("日志文件不存在")
            return

        try:
            with open(self.log_file_path, 'r', encoding='utf-8') as file:
                content = file.read()
                if not content:
                    self.text_edit.append("日志文件为空")
                    return

                # 将内容添加到文本编辑框
                self.text_edit.append(content)

            # 滚动到底部
            self.text_edit.verticalScrollBar().setValue(self.text_edit.verticalScrollBar().maximum())
        except Exception as e:
            self.text_edit.append(f"读取日志文件时发生错误: {e}")

    def update_log(self):
        try:
            if not os.path.exists(self.log_file_path):
                return

            with open(self.log_file_path, 'rb') as file:
                file.seek(0, os.SEEK_END)
                position = file.tell()
                buffer = bytearray()
                while position >= 0:
                    file.seek(position)
                    next_char = file.read(1)
                    if not next_char:  # 检查 next_char 是否为空
                        break
                    if next_char == b'\n' and len(buffer) > 0:
                        buffer.reverse()
                        line = bytes(buffer).decode('utf-8')
                        current_text = self.text_edit.toPlainText()
                        if not current_text.endswith(line):
                            self.text_edit.append(line)
                        buffer.clear()
                        if len(self.text_edit.toPlainText().split('\n')) >= 100:
                            break
                    buffer.append(next_char[0])
                    position -= 1
                if len(buffer) > 0:
                    buffer.reverse()
                    line = bytes(buffer).decode('utf-8')
                    current_text = self.text_edit.toPlainText()
                    if not current_text.endswith(line):
                        self.text_edit.append(line)
        except Exception as e:
            pass

        # 滚动到底部
        # self.text_edit.verticalScrollBar().setValue(self.text_edit.verticalScrollBar().maximum())
